using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;
using System.Text;

namespace BlazeApps.Library.Blog
{
    [Serializable()]
    public class BlogDetail : Csla.BusinessBase<BlogDetail>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _blogid = Guid.NewGuid();
        private string _title = string.Empty;
        private string _body = string.Empty;
        private Guid _userid = Guid.Empty;
        private SmartDate _createdate = new SmartDate(DateTime.Now);
        private Boolean _Private = false;

        [System.ComponentModel.DataObjectField(true, false)]
        public Guid Blogid
        {
            get
            {
                CanReadProperty("Blogid", true);
                return _blogid;
            }
        }

        public string Title
        {
            get
            {
                CanReadProperty("Title", true);
                return _title;
            }
            set
            {
                CanWriteProperty("Title", true);
                if (value == null)
                    value = string.Empty;
                if (!_title.Equals(value))
                {
                    _title = value;
                    PropertyHasChanged("Title");
                }
            }
        }

        public string Body
        {
            get
            {
                CanReadProperty("Body", true);
                return _body;
            }
            set
            {
                CanWriteProperty("Body", true);
                if (value == null)
                    value = string.Empty;
                if (!_body.Equals(value))
                {
                    _body = value;
                    PropertyHasChanged("Body");
                }
            }
        }

        public Guid Userid
        {
            get
            {
                CanReadProperty("Userid", true);
                return _userid;
            }
            set
            {
                CanWriteProperty("Userid", true);
                if (!_userid.Equals(value))
                {
                    _userid = value;
                    PropertyHasChanged("Userid");
                }
            }
        }

        public DateTime Createdate
        {
            get
            {
                CanReadProperty("Createdate", true);
                return _createdate.Date;
            }
        }

        public string CreatedateString
        {
            get
            {
                CanReadProperty("CreatedateString", true);
                return _createdate.Text;
            }
            set
            {
                CanWriteProperty("CreatedateString", true);
                if (value == null)
                    value = string.Empty;
                if (!_createdate.Equals(value))
                {
                    _createdate.Text = value;
                    PropertyHasChanged("CreatedateString");
                }
            }
        }

        public Boolean Private
        {
            get
            {
                return _Private;
            }
            set
            {
                CanWriteProperty("Private", true);
                if (!_Private.Equals(value))
                {
                    _Private = value;
                    PropertyHasChanged("Private");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _blogid;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            //
            // Title
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "Title");
            //
            // Body
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "Body");
            //
            // Createdate
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "CreatedateString");
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in BlogDetail
            //AuthorizationRules.AllowRead("Blogid", "BlogDetailReadGroup");
            //AuthorizationRules.AllowRead("Title", "BlogDetailReadGroup");
            //AuthorizationRules.AllowRead("Body", "BlogDetailReadGroup");
            //AuthorizationRules.AllowRead("Userid", "BlogDetailReadGroup");
            //AuthorizationRules.AllowRead("Createdate", "BlogDetailReadGroup");
            //AuthorizationRules.AllowRead("CreatedateString", "BlogDetailReadGroup");

            //AuthorizationRules.AllowWrite("Title", "BlogDetailWriteGroup");
            //AuthorizationRules.AllowWrite("Body", "BlogDetailWriteGroup");
            //AuthorizationRules.AllowWrite("Userid", "BlogDetailWriteGroup");
            //AuthorizationRules.AllowWrite("CreatedateString", "BlogDetailWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in BlogDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("BlogDetailViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in BlogDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("BlogDetailAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in BlogDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("BlogDetailEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in BlogDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("BlogDetailDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private BlogDetail()
        { /* require use of factory method */
        }

        public static BlogDetail NewBlogDetail()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a BlogDetail");
            return DataPortal.Create<BlogDetail>();
        }

        public static BlogDetail GetBlogDetail(Guid blogid)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a BlogDetail");
            return DataPortal.Fetch<BlogDetail>(new Criteria(blogid));
        }

        public static void DeleteBlogDetail(Guid blogid)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a BlogDetail");
            DataPortal.Delete(new Criteria(blogid));
        }

        public override BlogDetail Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a BlogDetail");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a BlogDetail");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a BlogDetail");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid Blogid;

            public Criteria(Guid blogid)
            {
                this.Blogid = blogid;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@blogid", criteria.Blogid);

            using(SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetBlogByBlogID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            dr.Read();
            _blogid = dr.GetGuid("blogid");
            _title = dr.GetString("title");
            _body = dr.GetString("body");
            _userid = dr.GetGuid("userid");
            _createdate = dr.GetSmartDate("createdate", _createdate.EmptyIsMin);
            _Private = dr.GetBoolean("private");
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertBlog.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@blogid", _blogid);
            DAL.AddParameter("@title", _title);
            DAL.AddParameter("@body", _body);
            DAL.AddParameter("@userid", _userid);
            DAL.AddParameter("@createdate", _createdate.DBValue);
            DAL.AddParameter("@private", _Private);
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }
        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddUpdateParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.UpdateBlog.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@blogid", _blogid);
            DAL.AddParameter("@title", _title);
            DAL.AddParameter("@body", _body);
            DAL.AddParameter("@private", _Private);
        }

        private void UpdateChildren(SqlConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_blogid));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);

            DAL.ExecuteNonQuery(Procs.DeleteBlog.ToString().Trim(), CommandType.Text, ConnectionState.Open);
            Procs.PurgeItemsByItemID(criteria.Blogid);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@blogid", DbType.Guid, criteria.Blogid);
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
